let behaviorsGetLocation = require('../../behaviors/getLocation.js')
const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import {
  showMsg
} from '../../../../utils/config.js'
import {
  reqConsumerHomeUpdate,
  reqConsumerHomeDel,
  reqConsumerList,
  reqGetPreId,
  reqExit,
} from '../../../../request/api.js';
Page({
  behaviors: [behaviorsGetLocation],
  data: {
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离

    form: {
      homeName: '',
      lng: '',
      lat: '',
      address: '',
      rooms: [],
      roomCount: 0,
    },
    avatar: '',
    showInputDialog: false,
    familyList: [],
    roles: 1, //1家庭创建者 2管理员 3普通成员
    homeConsumerId: "",
    showRoleSelection: false,
  },

  onLoad(options) {
    this.getParams()
  },

  onShow() {
    if (this.data.form.id) {
      this.getConsumerList() // 家庭用户列表
    }
  },
  // 成员列表
  async getConsumerList() {
    const res = await reqConsumerList({
      homeId: this.data.form.id
    })
    if (res.code != 20000) return showMsg(res.message);
    console.log(res);
    let roles
    let homeConsumerId
    res.data.rows.forEach(item => {
      if (item.mobile == app.globalData.mobile) {
        roles = item.role
        homeConsumerId = item.id
      }
    })
    this.setData({
      familyList: res.data.rows,
      roles,
      homeConsumerId
    })
  },

  getParams() {
    const _this = this
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('sendDataToDetail', function (res) {
      _this.setData({
        form: res.data
      })
      console.log('form', _this.data.form);
      _this.getConsumerList() // 家庭用户列表
    })
  },

  goRoom() {
    const _this = this
    wx.navigateTo({
      url: '/packageC/pages/room/room/room',
      events: {
        receiveDataFromRoom: function (res) {
          _this.setData({
            "form.roomCount": res.data
          });
          _this.notifyPageUpdataFoo()
        },
      },
      success: function (res) {
        res.eventChannel.emit('sendDataToRoom', {
          data: _this.data.form
        })
      }
    })
  },
  onMember(e) {
    console.log(e.currentTarget.dataset.item);
    let memberInfo = JSON.stringify(e.currentTarget.dataset.item)
    wx.navigateTo({
      url: `/packageC/pages/family/member/member?memberInfo=${memberInfo}&roles=${this.data.roles}`,
    })
  },


  onName() {
    this.setData({
      showInputDialog: true
    })
  },

  async inputDialogHandle(e) {
    console.log(e);

    const {
      actionType,
      value
    } = e.detail
    if (actionType === 'confirm') {
      if (!value) return showMsg("请填写家庭名称")
      this.setData({
        "form.homeName": value
      })
      await this.reqConsumerHomeUpdateFoo()
      this.setData({
        showInputDialog: false
      })
    } else {
      this.setData({
        showInputDialog: false
      })
    }
  },

  getLocation(location) {
    const {
      longitude,
      latitude,
      province,
      city,
      district,
      name
    } = location
    console.log(longitude,
      latitude, );

    this.setData({
      'from.lng': longitude,
      'form.lat': latitude,
      'form.address': name,
    })

    this.reqConsumerHomeUpdateFoo()
  },
  onExit() {
    Dialog.confirm({
        title: '温馨提示',
        message: '离开后，将不能查看和操作家庭里面的设备',
      })
      .then(async () => {
        const res = await reqExit({
          homeConsumerId: this.data.homeConsumerId
        })
        if (res.code != 20000) return showMsg(res.message);
        showMsg("操作成功")
        let {
          familyInfo
        } = app.globalData
        familyInfo.isUpdate = true
        app.globalData.familyInfo = familyInfo
        wx.setStorageSync('familyInfo', familyInfo);
        this.notifyPageUpdataFoo()
        wx.navigateBack()
      })
      .catch(() => {});
  },

  onDel() {
    if (this.data.familyList.length > 1) {
      wx.showModal({
        title: '删除失败',
        content: '请先移除设备和家庭成员',
        showCancel: false,
        confirmText: '确定',
      })
      return
    }
    Dialog.confirm({
        title: '温馨提示',
        message: '家庭删除后，所有数据会被清空、已添加设备会被解绑和重置',
      })
      .then(async () => {
        const res = await reqConsumerHomeDel(this.data.form.id)
        if (res.code != 20000) return showMsg(res.message);
        showMsg("已删除")
        let {
          familyInfo
        } = app.globalData
        if (familyInfo.id === this.data.form.id) {
          familyInfo.homeName = this.data.form.homeName
          familyInfo.isUpdate = true
          app.globalData.familyInfo = familyInfo
          wx.setStorageSync('familyInfo', familyInfo);
        }
        this.notifyPageUpdataFoo()
        wx.navigateBack()
      })
      .catch(() => {});
  },

  async reqConsumerHomeUpdateFoo() {
    const {
      form
    } = this.data
    const res = await reqConsumerHomeUpdate({
      homeId: form.id,
      homeName: form.homeName,
      lng: form.lng,
      lat: form.lat,
      address: form.address,
    })
    if (res.code != 20000) return showMsg(res.message);
    showMsg("修改成功", 'success')

    let {
      familyInfo
    } = app.globalData
    if (familyInfo.id === form.id) {
      familyInfo.homeName = form.homeName
      app.globalData.familyInfo = familyInfo
      wx.setStorageSync('familyInfo', familyInfo);
    }

    setTimeout(_ => {
      this.notifyPageUpdataFoo()
    }, 1000)
  },

  notifyPageUpdataFoo() {
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('receiveDataFromDetail', {
      isUpdataList: true
    });
  },
  // onShareAppMessage(res) {
  //   console.log(res);
  //   if (res.from === 'button') {
  //     let shareUserId = wx.getStorageSync('userId');
  //     const promise = new Promise((resolve, reject) => {
  //       reqGetPreId({
  //         role: 3,
  //         remark: "新成员"
  //       }).then(res => {
  //         console.log(res, '111');
  //         if (res.code != 20000) return showMsg(res.message);
  //         resolve({
  //           title: `${wx.getStorageSync('nickname')}邀请您加入${this.data.form.homeName}`,
  //           imagePath: './thumb.jpg',
  //           path: `/pages/index/index?preId=${res.data.preId}&homeId=${this.data.form.id}&shareUserId=${shareUserId}&nickname=${wx.getStorageSync('nickname')}&homeName=${this.data.form.homeName}&startTime=${new Date().getTime()}&totalTime=86400000`,
  //         })
  //       })
  //     })
  //     return {
  //       // 失效时间24小时  totalTime=86400000毫秒
  //       title: `${wx.getStorageSync('nickname')}邀请您加入${this.data.form.homeName}`,
  //       imagePath: './thumb.jpg',
  //       path: `/pages/index/index?shareUserId=${shareUserId}&startTime=${new Date().getTime()}&totalTime=86400000`,
  //       promise
  //     }
  //   }
  // },
  onAdd() {
    this.setData({
      showRoleSelection: true
    })
  },
  async confirmRoomSelection(e) {
    const {
      action,
      roomInfo
    } = e.detail
    console.log(roomInfo, 'e');
    if (action == 'confirm') {
      wx.navigateTo({
        url: `/packageC/pages/family/addMember/addMember?role=${roomInfo.id}&homeName=${this.data.form.homeName}&homeId=${this.data.form.id}`,
      })
      this.setData({
        showRoleSelection: false,
      })
    } else {
      this.setData({
        showRoleSelection: false
      })
    }
  },

})